/**
 * 基金组合列表
 * @author tongsitong
 */
import styled from "styled-components";
import { BorderRedBtn, TableOptBtn } from "@/components/Button";
import { MagnifyGlass, RedPlus } from "@/components/Icon";
import SInput from "@/components/Input";
import { PageWrapper } from "@/components/PageWrapper";
import STable from "@/components/Table";
import { Title } from "@/components/Title";
import { useEffect, useRef, useState } from "react";
import uploadIcon from "@/assets/icons/icon-upload.png";
import updateDataIcon from "@/assets/icons/icon-update-data.png";
import listReviewIcon from "@/assets/icons/icon-list-review.png";
import settingIcon from "@/assets/icons/icon-config-settings.png";
import {
  getPortfolioList,
  getBenchMarkList,
  deletePortfolio,
  createPortfolio,
  calculatePortfolio,
  updatePortfolio,
  isPortfolioRunning,
} from "./service";
import { Dropdown, Menu, message, Select } from "antd";
import styles from "./index.less";
import UploadFileModal from "@/components/UploadFileModal";
import Label from "@/components/Label";
import SSelect from "@/components/Select";
import { FlexDiv } from "@/components/FOF/SelectInput";
import { UploadFile } from "@/components/UploadFile";
import { ThresholdSet } from "@/components/FOF/ThresholdSet";
import { PreviewPosition } from "@/components/FOF/PreviewPosition";
import WarnModal from "@/components/Modals/WarnModal";
import { PreviewTable } from "@/components/FOF/PreviewTable";
import { Divider } from "@/components/Divider";
import { PreviewHint } from "@/components/FOF/PreviewHint";
import { PreviewFooter } from "@/components/FOF/PreviewFooter";
import { convertUrl, isAuthored } from "@/utils/utils";
import LinkWebsocket from "@/hook/useWebsocket";
import { Link, useNavigate } from "react-router-dom";
interface selectProps {
  value: string;
  label?: string;
}

type ObjectT = {
  [key: string]: string | number;
};
let defaultBenchmark: selectProps = null;

const UPDATING_INFO = "组合正在进行数据处理，请稍后查看。";
const UPDATEFAIL_INFO = "数据任务处理失败，请重新更新数据";
const DELETE_INFO = "即将删除组合，是否确定？";
const LINE_WIDTH = { minWidth: 440, width: "calc(100% - 100px)" }; // 每行宽度props

export function PortfolioListPage() {
  let navigate = useNavigate();
  const [searchValue, setSearchValue] = useState("");
  const [portfolioList, setPorforlioList] = useState([]);
  const [current, setCurrent] = useState(1); // 当前页
  const [total, setTotal] = useState(1); // 总条数
  const [pageSize, setPageSize] = useState(10);
  const [loading, setLoading] = useState(true);
  const [infoPopVisible, setInfoPopVisible] = useState(false);
  const [benchmark, setBenchmark] = useState<selectProps>(); // select的选中值 {label: '中证混合基金指数（选这个）', value: '6654', key: '6654', disabled: undefined}
  // const [benchmarkCode, setBenchmarkCode] = useState("");
  const [file, setFile] = useState({});
  const [benchmarkList, setBenchmarkList] = useState([]); // 业绩基准列表
  const [modalVisible, setModalVisible] = useState(false);
  const [warnInfo, setWarnInfo] = useState(""); // 警告文字
  const [editPortfolio, setEditPortfolio] = useState<{ [key: string]: string }>(
    {},
  ); // 正在处理的组合
  const [warnPopVisible, setWarnPopVisible] = useState(false); // 警告弹窗
  const [selectedFofCode, setSelectedFofCode] = useState("");
  const [selectedFofName, setSelectedFofName] = useState("");
  const [excelContent, setExcelContent] = useState([]); // 上传文件内容
  const [emptyVisible, setEmptyVisible] = useState(true); // 是否显示数据为空
  const [fileId, setFileId] = useState(""); // 上传文件id
  const [previewVisible, setPreviewVisible] = useState(false); // 持仓预览部分是否可见
  const [bondLowerBound, setBondLowerBound] = useState(0); // 债券阈值下限
  const [bondUpperBound, setBondUpperBound] = useState(0); // 债券阈值上限
  const [stockLowerBound, setStockLowerBound] = useState(0); // 股票阈值下限
  const [stockUpperBound, setStockUpperBound] = useState(0); // 股票阈值上限
  const [portfolioName, setPortfolioName] = useState(""); // 组合名称
  // const [perfComBenchmark, setPerfComBenchmark] = useState(""); // 业绩基准名称
  const [isNameError, setIsNameError] = useState(false); // 组合名称input框是否错了
  const [isStockBoundError, setIsStockBoundError] = useState(false); // 组合名称input框是否错了
  const [isBondBoundError, setIsBondBoundError] = useState(false); // 组合名称input框是否错了
  const [isFileError, setIsFileError] = useState(false); // 文件没有上传出红框
  const [modalTitle, setModalTitle] = useState("新增组合"); // 弹窗标题
  const [wsMsg, setWsMsg] = useState(""); // 读取进度的websocket
  const [localWsMsg, setLocalWsMsg] = useState<ObjectT>(null); //本地缓存wsmsg
  const [isExcelError, setIsExcelError] = useState(false); // 持仓列表出红框

  const uploadRef = useRef(null); //上传文件子组件ref
  const stockThresholdRef = useRef(null); // 阈值设置ref
  const bondThresholdRef = useRef(null); // 阈值设置ref

  const EDIT_KEY = "1";
  const DELETE_KEY = "2";

  // 清空文件内容
  const resetFile = () => {
    setFile({});
    setFileId("");
    uploadRef.current.handleClearFile();
    setEmptyVisible(true);
    setPreviewVisible(false);
    setExcelContent([]);
  };

  // 清空UI
  const resetUI = () => {
    resetFile();

    setEditPortfolio({});
    // setBenchmarkCode("");
    setBenchmark(defaultBenchmark);
    setBondLowerBound(0);
    setBondUpperBound(0);
    // setPerfComBenchmark("");
    setPortfolioName("");
    setStockLowerBound(0);
    setStockUpperBound(0);

    setIsNameError(false);
    setIsStockBoundError(false);
    setIsBondBoundError(false);
    setIsFileError(false);
    setIsExcelError(false);

    stockThresholdRef.current.clearError();
    bondThresholdRef.current.clearError();
  };

  // 上传文件后收到的返回数据
  const getResData = (res) => {
    if (res?.code != 0) {
      // 弹窗报错
      // message.error(res.errMsg || res.msg || res.message)
      setWarnInfo("文件解析失败，请检查上传文件格式。");
      setWarnPopVisible(true);
      resetFile();
      return;
    }
    if (res?.data.fileId === "1") {
      setIsExcelError(true);
    } else {
      setIsExcelError(false);
    }
    setExcelContent(res?.data?.fundList);
    setFileId(res?.data?.fileId);
    setIsFileError(false);
  };

  // 新增组合弹窗显示
  const addPortfolio = () => {
    setInfoPopVisible(true);
    setModalTitle("新增组合");
  };

  /**
   * 检查组合是否在更新
   * @param portfolioCode
   * @param notRunCallback 如果没有在更新的回调函数
   * @param runCallback 如果在更新的回调函数
   * @param check 0 需要校验status如链接，不传就是不需要如操作类即使失败也可以执行
   */
  const checkRunning = async (
    portfolioCode: string,
    notRunCallback?: any,
    check?: string,
  ) => {
    const isRunning = await isPortfolioRunning({
      portfolioCode,
      check,
    });
    if (isRunning.msg == "1" && check != "0") {
      // 正在跑批
      message.error("该组合正在更新，请稍后重试");
      return;
    }
    if (check == "0") {
      // 链接点进来，状态1和2弹窗不同，0才可以进入
      if (isRunning.msg == "1") {
        // 正在跑批
        setWarnPopVisible(true);
        setWarnInfo(UPDATING_INFO);
        return;
      }
      if (isRunning.msg == "2") {
        // 异常
        setWarnPopVisible(true);
        setWarnInfo(UPDATEFAIL_INFO);
        return;
      }
    }
    notRunCallback && notRunCallback();
  };

  // 更新数据
  const updateData = async (record) => {
    checkRunning(record.portfolioCode, () => {
      calculatePortfolio({
        portfolioCode: record.portfolioCode,
      });
    });
  };

  // 组合名称input change
  const changeName = (value) => {
    setPortfolioName(value);
    setIsNameError(value.trim() === "");
  };

  // 改阈值上下限
  const changeThreshold = () => {
    if (
      parseFloat(bondUpperBound.toString()) <=
        parseFloat(bondLowerBound.toString()) ||
      parseFloat(stockUpperBound.toString()) <=
        parseFloat(stockLowerBound.toString())
    ) {
      setIsBoundError(true);
    } else {
      setIsBoundError(false);
    }
  };

  // 新增、编辑组合提交
  const handleSubmitInfo = async () => {
    // check before submit
    let newErrorFlag = false; // 新建是否有报错
    let benchmarkCode = benchmark.value;
    let perfComBenchmark = benchmark.label; // 业绩基准名称

    // 新增组合必须上传持仓文件
    if (!fileId && modalTitle.indexOf("新增") > -1) {
      setIsFileError(true);
      newErrorFlag = true;
    }

    if (
      [
        benchmarkCode,
        bondLowerBound,
        bondUpperBound,
        perfComBenchmark,
        portfolioName,
        stockLowerBound,
        stockUpperBound,
      ].indexOf("") > -1
    ) {
      setIsNameError(portfolioName === "");
      newErrorFlag = true;
    }

    stockThresholdRef.current.checkError();
    bondThresholdRef.current.checkError();

    // 什么也不输的时候需要检查上限是否大于下限
    if (
      parseFloat(bondUpperBound.toString()) <=
      parseFloat(bondLowerBound.toString())
    ) {
      setIsBondBoundError(true);
      newErrorFlag = true;
    }
    if (
      parseFloat(stockUpperBound.toString()) <=
      parseFloat(stockLowerBound.toString())
    ) {
      setIsStockBoundError(true);
      newErrorFlag = true;
    }

    // 检查上传文件是否有代码错误
    if (fileId === "1") {
      newErrorFlag = true;
    }

    if (newErrorFlag) {
      return;
    }

    let response = null;

    if (modalTitle.indexOf("新增") > -1) {
      response = await createPortfolio({
        benchmarkCode,
        bondLowerBound,
        bondUpperBound,
        perfComBenchmark,
        portfolioName,
        stockLowerBound,
        stockUpperBound,
        fileId,
      });
    } else {
      response = await updatePortfolio({
        portfolioCode: editPortfolio.portfolioCode,
        benchmarkCode,
        bondLowerBound,
        bondUpperBound,
        perfComBenchmark,
        portfolioName,
        stockLowerBound,
        stockUpperBound,
        fileId,
        id: editPortfolio.id,
        // establishDate
      });
    }
    if (response.code == "0") {
      searchFof();
    }
    resetUI();
    setInfoPopVisible(false);
  };

  // 取消新增组合弹窗
  const handleCancelAdd = () => {
    resetUI();
    setInfoPopVisible(false);
  };

  // 上传持仓文件
  const uploadPosition = async (record) => {
    checkRunning(record.portfolioCode, () => {
      setSelectedFofCode(record.portfolioCode);
      setSelectedFofName(record.portfolioName);
      setModalVisible(true);
    });
  };

  // 配置参数
  const gotoSetting = (record) => {
    let url = `/com-params?portfolioCode=${record.portfolioCode}`;
    process.env.NODE_ENV !== "production"
      ? navigate(url)
      : top.window.postMessage(
          {
            url: `/desert-star${url}`,
          },
          location.origin,
        );
  };

  // 表格点更多操作
  const handleClickMenu = async (e, record: any) => {
    if (e.key === EDIT_KEY) {
      checkRunning(record.portfolioCode, () => {
        setEditPortfolio(record);
        setInfoPopVisible(true);
        setModalTitle("编辑组合");
        setBenchmark({
          value: record.benchmarkCode,
        });
        setBondLowerBound(record.bondLowerBound);
        setBondUpperBound(record.bondUpperBound);
        setPortfolioName(record.portfolioName);
        setStockLowerBound(record.stockLowerBound);
        setStockUpperBound(record.stockUpperBound);
      });
    } else if (e.key === DELETE_KEY) {
      checkRunning(record.portfolioCode, () => {
        setEditPortfolio(record);
        setWarnInfo(DELETE_INFO);
        setWarnPopVisible(true);
      });
    }
  };
  // 警告弹窗确认
  const onWarnConfirm = () => {
    if (warnInfo.indexOf(DELETE_INFO) > -1) {
      deletePortfolio({
        portfolioCode: editPortfolio?.portfolioCode,
      }).then((res) => {
        if (res?.code == 0) {
          if (portfolioList.length == 1) {
            // 删除的是最后一页最后一行
            if (current != 1) {
              setCurrent(current - 1);
            }
          } else {
            // 停留在当前页
            afterChangePage();
          }
        }
      });
    }
    if (warnInfo.indexOf(UPDATEFAIL_INFO) > -1) {
      updateData(editPortfolio);
    }
    setWarnPopVisible(false);
  };

  const menu = (record: any) => (
    <Menu
      onClick={(e) => handleClickMenu(e, record)}
      className={styles.cusMenu}
    >
      <>
        <Menu.Item key={EDIT_KEY}>编辑</Menu.Item>
        <Menu.Item key={DELETE_KEY}>删除</Menu.Item>
      </>
    </Menu>
  );

  const columns = [
    {
      title: "组合名称",
      dataIndex: "portfolioName",
      key: "portfolioName",
      render: (text: string, record: any) => {
        let url = `/portfolio-overview?id=${
          record?.portfolioCode
        }&name=${convertUrl(record?.portfolioName)}`;
        return process.env.NODE_ENV !== "production" ? (
          <Link to={{ pathname: url }}> {text}</Link>
        ) : (
          <a
            onClick={async () => {
              setEditPortfolio(record);
              checkRunning(
                record.portfolioCode,
                () => {
                  top.window.postMessage(
                    { url: `/desert-star${url}` },
                    location.origin,
                  );
                },
                "0",
              );
            }}
          >
            {text}
          </a>
        );
        // DetailLink(
        //   `/portfolio-overview?id=${record?.portfolioCode}&name=${convertUrl(
        //     record?.portfolioName,
        //   )}`,
        //   text,
        // ),
      },
    },
    {
      title: "组合成立日期",
      dataIndex: "establishDate",
      key: "establishDate",
      render: (text: string) => text || "-",
    },
    {
      title: "最新调仓日期",
      dataIndex: "latestAdjustDate",
      key: "latestAdjustDate",
      render: (text: string) => text || "-",
    },
    {
      title: "数据处理进度",
      dataIndex: "latestAdjustDate",
      key: "latestAdjustDate",
      width: 200,
      render: (text: string, record: any) => {
        let array10 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
        let progressBar = null;
        let progress = 0; // 条子数目
        let realData = 0;

        if (!localWsMsg) {
          // 第一次取列表返回数据
          // return "加载中...";
          if (record.status == "2") {
            // 0表示正常，1表示处理中，2表示异常
            return (
              <>
                <ProgressText color="#E64A00">解析失败，请更新</ProgressText>
              </>
            );
          } else {
            realData = Math.floor(record.percent);
            progress = Math.floor(record.percent / 10);
          }
        } else {
          // 取ws里数据
          // 向下取整
          realData = localWsMsg[record.portfolioCode];
          if (realData == -1) {
            return (
              <>
                <ProgressText color="#E64A00">解析失败，请更新</ProgressText>
              </>
            );
          }
          if (isNaN(realData)) {
            if (record.status == "2") {
              return (
                <>
                  <ProgressText color="#E64A00">解析失败，请更新</ProgressText>
                </>
              );
            }
            // 还在跑
            realData = record.percent;
          }
          realData = Math.floor(realData);
        }
        progress = Math.floor(realData / 10); // 条子数目
        if (progress >= 10) {
          progressBar = array10.map((item) => {
            return <SingleProgressBar color="green" />;
          });
        } else {
          progressBar = array10.map((item, index) => {
            if (index < progress) {
              return <SingleProgressBar color="red" />;
            } else {
              return <SingleProgressBar color="grey" />;
            }
          });
        }
        return (
          <>
            <ProgressText>{realData}%</ProgressText>
            <InlineFlex>{progressBar}</InlineFlex>
          </>
        );

        // if (!isNaN(realData)) {
        //   let progress = Math.floor(realData / 10); // 条子数目
        //   // const $progressBar = document.createElement("div");
        //   // let itemHtmls: any = [];

        //   if (realData >= 100) {
        //     // let i = 0;
        //     // while(i<10){
        //     //   itemHtmls.push(`<singleprogressbar></singleprogressbar>`)
        //     //   i++;
        //     // }
        //     // $progressBar.innerHTML = itemHtmls.join('')
        //     // return (
        //     //   $progressBar
        //     // )
        //     progressBar = array10.map((item) => {
        //       return <SingleProgressBar color="green" />;
        //     });
        //   } else {
        //     progressBar = array10.map((item, index) => {
        //       if (index < progress) {
        //         return <SingleProgressBar color="red" />;
        //       } else {
        //         return <SingleProgressBar color="grey" />;
        //       }
        //     });
        //   }
        //   return (
        //     <>
        //       <ProgressText>{realData}%</ProgressText>
        //       <InlineFlex>{progressBar}</InlineFlex>
        //     </>
        //   );
        // } else {
        //   progressBar = array10.map((item) => {
        //     return <SingleProgressBar color="grey" />;
        //   });
        //   return (
        //     <>
        //       <ProgressText>--</ProgressText>
        //       <InlineFlex>{progressBar}</InlineFlex>
        //     </>
        //   );
        // }
      },
    },
    {
      title: "业绩比较基准",
      dataIndex: "perfComBenchMark",
      key: "perfComBenchMark",
      render: (text: string) => text || "-",
    },
    {
      title: "操作",
      key: "option",
      valueType: "option",
      width: 180,
      render: (item: any, record: any) => {
        return (
          <>
            {isAuthored("UPLOAD_POSITION") && (
              <TableOptBtn
                img={uploadIcon}
                text="上传持仓文件"
                onClick={() => uploadPosition(record)}
                style={{ marginRight: "24px" }}
              />
            )}
            {isAuthored("CONFIG_PARM") && (
              <TableOptBtn
                img={settingIcon}
                style={{ marginRight: "24px" }}
                text="配置参数"
                onClick={() => gotoSetting(record)}
              />
            )}
            {isAuthored("UPDATE_DATA") && (
              <TableOptBtn
                img={updateDataIcon}
                style={{ marginRight: "24px" }}
                text="更新数据"
                onClick={() => updateData(record)}
              />
            )}
            {isAuthored("EDIT_PORTFOLIO") && (
              <Dropdown overlay={menu(record)}>
                <span>
                  <img
                    style={{ width: 14, height: 14, marginBottom: 3 }}
                    src={listReviewIcon}
                  />
                  <span style={{ color: "#1F51A4" }}>更多</span>
                </span>
              </Dropdown>
            )}
          </>
        );
      },
    },
  ];

  // 搜索框
  const onChange = (value) => {
    setSearchValue(value);
  };

  const changeBenchMark = (item: selectProps) => {
    setBenchmark(item);
  };

  // 查找组合
  const searchFof = () => {
    if (current == 1) {
      afterChangePage();
    } else {
      setCurrent(1);
    }
  };

  // 分页
  function changePage(obj: any) {
    let newPageSize = obj.pageSize;
    let newCurrent = obj.current;
    if (pageSize != newPageSize) {
      newCurrent = 1;
      setPageSize(newPageSize);
    }
    if (current != newCurrent) {
      setCurrent(newCurrent);
    }
    // let params = {
    //   keyword: searchValue,
    //   current: newCurrent,
    //   size: newPageSize,
    // };
    // getTableData(params);
  }

  const getTableData = (data?: any) => {
    setLoading(true);
    let params = Object.assign({}, data);
    getPortfolioList(params).then((res) => {
      setLoading(false);
      setTotal(res.data?.total);
      setPorforlioList(res.data?.records);
    });
  };

  const afterChangePage = () => {
    let params = { keyword: searchValue, current, size: pageSize };
    getTableData(params);
  };

  useEffect(() => {
    afterChangePage();
  }, [current, pageSize]);

  useEffect(() => {
    // getTableData({
    //   current: 1,
    //   size: 10,
    // });
    getBenchMarkList().then((res) => {
      setBenchmarkList(res?.data);
      if (res?.data.length > 0) {
        defaultBenchmark = {
          label: res?.data[0].benchmarkName,
          value: res?.data[0].benchmarkCode,
        };
        setBenchmark(defaultBenchmark);
      }
    });
    LinkWebsocket("progressBar", setWsMsg);
  }, []);

  useEffect(() => {
    if (excelContent?.length > 0) {
      setEmptyVisible(false);
      setPreviewVisible(true);
    }
  }, [excelContent]);

  useEffect(() => {
    if (!wsMsg) return;

    try {
      let obj: ObjectT = JSON.parse(wsMsg);
      let newObj: ObjectT = Object.assign({}, localWsMsg);

      if (!localWsMsg) {
        // 第一次收到消息
        setLocalWsMsg(JSON.parse(wsMsg));
      } else {
        // 把接收到的差异消息赋值
        for (let k in obj) {
          newObj[k] = obj[k];
        }
        setLocalWsMsg(newObj);
      }
    } catch (error) {
      console.log(error);
    }
  }, [wsMsg]);

  return (
    <PageWrapper>
      <div
        style={{
          position: "relative",
          display: "flex",
          justifyContent: "space-between",
        }}
      >
        <Title>基金组合</Title>
        <div style={{ display: "flex" }}>
          <SInput
            placeholder="请输入组合名称"
            value={searchValue}
            onChange={onChange}
            onPressEnter={searchFof}
            prefix={<MagnifyGlass />}
            allowClear
          />
          {isAuthored("ADD_PORTFOLIO") && (
            <>
              <VerticleBar />
              <div style={{ width: 88 }}>
                <BorderRedBtn onClick={addPortfolio}>
                  <RedPlus />
                  新增组合
                </BorderRedBtn>
              </div>
            </>
          )}
        </div>
      </div>
      <STable
        dataSource={{
          records: portfolioList,
          current,
          total,
          size: pageSize,
          pageSizeOptions: ["10", "50", "100"],
        }}
        rowKey={(r) => r.id}
        columns={columns}
        onChange={changePage}
        style={{ whiteSpace: "nowrap", marginTop: 12 }}
        scroll={{ x: true }}
        loading={loading}
      ></STable>
      {/* 新增、编辑组合 */}
      <UploadFileModal
        wrapClassName={styles.edit_modal}
        modalWidth={600}
        title={modalTitle}
        okText="提交"
        leftFooter={<PreviewFooter />}
        bodyStyle={{ paddingBottom: 0 }}
        visible={infoPopVisible}
        toggleModal={handleCancelAdd}
        handleOk={handleSubmitInfo}
        mask={!warnPopVisible} //todo如果有另一个modal再弹modal则不需要遮罩
      >
        <div className={styles.pop}>
          <FlexDiv mb="20px">
            <Label className={styles.label}>组合名称</Label>
            <SInput
              placeholder="请输入"
              style={LINE_WIDTH}
              isError={isNameError}
              value={portfolioName}
              onChange={changeName}
              maxLength={20}
            ></SInput>
          </FlexDiv>
          <FlexDiv mb="20px">
            <Label className={styles.label}>业绩比较基准</Label>
            <div style={{width: "calc(100% - 112px)"}}>
              <SSelect
                labelInValue
                suffixIcon={<div className="findfit_icon_arrow " />}
                value={benchmark}
                onChange={changeBenchMark}
                style={{ width: "100%", minWidth: 440 }}
              >
                {benchmarkList.map((item) => {
                  return (
                    <Select.Option
                      key={item.benchmarkCode}
                      value={item.benchmarkCode}
                    >
                      {item.benchmarkName}
                    </Select.Option>
                  );
                })}
              </SSelect>
            </div>
          </FlexDiv>
          <FlexDiv mb="4px">
            <Label className={styles.label}>资产阈值设定</Label>
            <ThresholdSet
              title="股票"
              ref={stockThresholdRef}
              upperValue={stockUpperBound}
              lowerValue={stockLowerBound}
              setUpperValue={setStockUpperBound}
              setLowerValue={setStockLowerBound}
              isBoundError={isStockBoundError}
              setIsBoundError={setIsStockBoundError}
            ></ThresholdSet>
          </FlexDiv>
          <FlexDiv mb="0px">
            <Label className={styles.label}></Label>
            <ThresholdSet
              title="债券"
              ref={bondThresholdRef}
              upperValue={bondUpperBound}
              lowerValue={bondLowerBound}
              setUpperValue={setBondUpperBound}
              setLowerValue={setBondLowerBound}
              isBoundError={isBondBoundError}
              setIsBoundError={setIsBondBoundError}
            ></ThresholdSet>
          </FlexDiv>
          <FlexDiv justify="flex-end">
            <ThresholdHint
              color={
                isStockBoundError || isBondBoundError
                  ? "#E64A00"
                  : "transparent"
              }
            >
              上限必须大于下限
            </ThresholdHint>
          </FlexDiv>
          <FlexDiv mb="16px">
            <Label className={styles.label}>持仓文件</Label>
            <UploadFile
              setFile={setFile}
              style={{ ...LINE_WIDTH, background: "#F5F6F8" }}
              ref={uploadRef}
              setResData={getResData}
              isError={isFileError}
            ></UploadFile>
          </FlexDiv>
          {/* 新增没有覆盖提示 */}
          {previewVisible && (
            <>
              <Divider>
                <span>持仓文件预览</span>
              </Divider>
              <PreviewTable
                style={{ marginTop: 4 }}
                emptyVisible={emptyVisible}
                excelContent={excelContent}
                isError={isExcelError}
              />
              <PreviewHint
                visible={!emptyVisible && modalTitle.indexOf("新增") < 0}
              />
            </>
          )}
        </div>
      </UploadFileModal>

      {/* 上传持仓文件 */}
      <PreviewPosition
        visible={modalVisible}
        setVisible={setModalVisible}
        id={selectedFofCode}
        name={selectedFofName}
        setWarnInfo={setWarnInfo}
        okText="提交"
        setWarnPopVisible={setWarnPopVisible}
        mask={!warnPopVisible} //todo如果有另一个modal再弹modal则不需要遮罩
        afterConfirm={afterChangePage}
      />
      <WarnModal
        zIndex={2000}
        content={warnInfo}
        visible={warnPopVisible}
        onClickOk={onWarnConfirm}
        onClickCancel={() => {
          setWarnPopVisible(false);
        }}
        okText={warnInfo.indexOf(UPDATEFAIL_INFO) > -1 ? "更新" : "确认"}
        cancelText={warnInfo.indexOf(UPDATING_INFO) > -1 ? null : "取消"}
      />
    </PageWrapper>
  );
}

const VerticleBar = styled.div`
  width: 1px;
  height: 12px;
  background: #e5e5e5;
  position: relative;
  top: 8px;
  margin: 0 8px;
`;

// 进度条每根条子
const SingleProgressBar = styled.div`
  width: 2px;
  background-color: ${(props) =>
    props.color === "red"
      ? "#E85C36"
      : props.color === "grey"
      ? "#D9DDE8"
      : "#17a785"};
  height: 10px;
  display: inline-block;
  border-radius: 2px;
  margin-right: 2px;
  contain: content;
`;

// 进度百分比
const ProgressText = styled.span`
  color: ${(props) => props.color || "#35425e"};
  font-size: 13px;
  margin-right: 6px;
  display: inline-block;
  text-align: right;
  min-width: 34px;
`;

const InlineFlex = styled.div`
  display: inline-flex;
`;

// 阈值设定的错误提示
const ThresholdHint = styled.span`
  font-size: 12px;
  transform: scale(0.83);
  color: ${(props) => props.color || "#E64A00"};
  height: 24px;
  line-height: 24px;
  display: inline-block;
  white-space: nowrap;
  left: 4px;
`;
